package com.shujia.wyh.mr.tuijian;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class MyPersonMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //tom hello hadoop cat
        /**
         * <"tom-hello",1>
         * <"tom-hadoop",1>
         * <"tom-cat",1>
         * <"hello-hadoop",-1>
         * <"hello-cat",-1>
         * <"hadoop-cat",-1>
         *
         * hadoop tom hive world hello
         */
        //先变成java中字符串形式
        String line = value.toString();
        //按照空格切分
        String[] persons = line.split(" ");
        for (int i = 1; i < persons.length; i++) {
            context.write(new Text(order(persons[0],persons[i])), new LongWritable(1L));
            for (int j = i + 1; j < persons.length; j++) {
                context.write(new Text(order(persons[i],persons[j])), new LongWritable(-1L));
            }
        }
    }

    /**
     * 定义一个方法确定相同的两个人顺序是一样的
     * <p>
     * ASCII码小的在前
     * <p>
     * hive-world
     */
    public String order(String p1, String p2) {
        String s = null;

        if (p1.compareTo(p2) < 0) {
            s = p1 + "-" + p2;
        } else if (p1.compareTo(p2) > 0) {
            s = p2 + "-" + p1;
        }
        return s;
    }
}
